package com.bh.web.controller.system;

import cn.hutool.core.util.ReUtil;
import com.bh.common.annotation.Log;
import com.bh.common.constant.Constants;
import com.bh.common.core.controller.BaseController;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.core.domain.entity.SysCustomerUser;
import com.bh.common.core.domain.model.LoginUser;
import com.bh.common.core.page.TableDataInfo;
import com.bh.common.enums.BusinessType;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.poi.ExcelUtil;
import com.bh.system.service.ISysCustomerUserService;
import com.bh.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户信息Controller
 *
 * @author slx
 * @date 2023-06-15
 */
@RestController
@RequestMapping("/system/customerUser")
public class SysCustomerUserController extends BaseController {
    @Autowired
    private ISysCustomerUserService sysCustomerUserService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询用户信息列表
     */
    @ApiOperation("查询用户信息列表")
    @PreAuthorize("@ss.hasPermi('system:customerUser:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysCustomerUser sysCustomerUser) {
        startPage();
        List<SysCustomerUser> list = sysCustomerUserService.selectUserList(sysCustomerUser);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:customerUser:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysCustomerUser sysCustomerUser) {
        List<SysCustomerUser> list = sysCustomerUserService.selectUserList(sysCustomerUser);
        ExcelUtil<SysCustomerUser> util = new ExcelUtil<>(SysCustomerUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @ApiOperation("获取用户信息详细信息")
    @PreAuthorize("@ss.hasPermi('system:customerUser:query')")
    @GetMapping("/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(sysCustomerUserService.selectUserById(userId));
    }

    /**
     * 修改用户信息
     */
    @ApiOperation("修改用户信息")
    @PreAuthorize("@ss.hasPermi('system:customerUser:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysCustomerUser user) {
        if (!sysCustomerUserService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getNickName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysCustomerUserService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getNickName() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(getUsername());
        int num = sysCustomerUserService.updateUser(user);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginUser.setUser(userService.selectUserById(user.getUserId()));
        return toAjax(num);
    }

    /**
     * 删除用户信息
     */
    @ApiOperation("删除用户信息")
    @PreAuthorize("@ss.hasPermi('system:customerUser:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(sysCustomerUserService.deleteUserByIds(userIds));
    }



    @PreAuthorize("@ss.hasPermi('system:customerUser:resetPwd')")
    @Log(title = "重置密码" , businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public AjaxResult resetPwdSave(SysCustomerUser user) {
        // 检测密码复杂度，必须为 6-20位，且包含字母、数字、符号
        if (!ReUtil.isMatch(Constants.REGEXP, user.getPassword())) {
            return error("密码必须包含大写字母 、数字、 特殊字符（四种里至少三种，且至少6位）");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (sysCustomerUserService.resetUserPwd(user) > 0) {
            if (getUserId().longValue() == user.getUserId().longValue()) {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                loginUser.setUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }
}
